package com.hzcx.app.simplechat.ui.mine;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.bean.UpLoadImgBean;
import com.hzcx.app.simplechat.chat.ChatUtil;
import com.hzcx.app.simplechat.chat.constant.ChatConstant;
import com.hzcx.app.simplechat.common.Common;
import com.hzcx.app.simplechat.ui.chat.ChatShareUserActivity;
import com.hzcx.app.simplechat.ui.chat.event.ChatShareUserEvent;
import com.hzcx.app.simplechat.ui.home.AddFriendActivity;
import com.hzcx.app.simplechat.ui.main.MainActivity;
import com.hzcx.app.simplechat.ui.mine.contract.MineUserInfoContract;
import com.hzcx.app.simplechat.ui.mine.event.EditUserInfoSuccesEvent;
import com.hzcx.app.simplechat.ui.mine.presenter.MineUserInfoPresenter;
import com.hzcx.app.simplechat.ui.moment.MomentCreateActivity;
import com.hzcx.app.simplechat.ui.moment.MomentInfoActivity;
import com.hzcx.app.simplechat.ui.moment.adapter.MomentAdapter;
import com.hzcx.app.simplechat.ui.moment.bean.MomentBean;
import com.hzcx.app.simplechat.ui.moment.event.DeleteCommentEvent;
import com.hzcx.app.simplechat.ui.moment.event.DeleteMomentEvent;
import com.hzcx.app.simplechat.ui.moment.event.MomentCreateEvent;
import com.hzcx.app.simplechat.ui.publicui.CaptureResultActivity;
import com.hzcx.app.simplechat.ui.publicui.PublicRoundDialog;
import com.hzcx.app.simplechat.ui.publicui.ShareActivity;
import com.hzcx.app.simplechat.ui.publicui.WebViewActivity;
import com.hzcx.app.simplechat.ui.user.UserInfoActivity;
import com.hzcx.app.simplechat.ui.user.bean.UserInfoBean;
import com.hzcx.app.simplechat.ui.user.enums.SexEnum;
import com.hzcx.app.simplechat.util.TextHttpUtil;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.app.AppHelper;
import com.hzcx.app.simplechat.util.down.DownLoadUtil;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.glide.GlideUtils;
import com.hzcx.app.simplechat.util.image.ImageUtil;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.qrcode.QRCodeParseUtils;
import com.hzcx.app.simplechat.util.toast.ToastUtils;
import com.hzcx.app.simplechat.view.autogridview.PhotoLoader;
import com.hzcx.app.simplechat.view.autogridview.PhotoProgressUi;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import indi.liyi.viewer.ImageViewer;
import indi.liyi.viewer.listener.OnItemLongPressListener;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

/**
 * 我的-用户信息及动态列表页面
 */
public class MineUserInfoActivity extends BaseActivity<MineUserInfoPresenter> implements MineUserInfoContract.View, OnRefreshListener,
        BaseQuickAdapter.RequestLoadMoreListener, MomentAdapter.OnItemClickCallback, BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.rv_moment)
    RecyclerView rvMoment;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    @BindView(R.id.imageViewer)
    ImageViewer imageViewer;
    @BindView(R.id.ll_null)
    LinearLayout llNull;
    private List<MomentBean> momentData;
    private MomentAdapter momentAdapter;

    private ImageView ivHead;
    private TextView tvNickName;
    private TextView tvUserId;
    private TextView tvCity;
    private TextView tvSign;
    private ImageView ivSex;
    private TextView tvEditUserInfo;

    private int page = 1;
    private boolean isRefresh = true;
    private ImageView saveImageView;
    private String collectImgUrl;

    @Override
    public int getLayout() {
        return R.layout.activity_mine_userinfo;
    }

    @Override
    public void initPresenter() {
        mPresenter = new MineUserInfoPresenter();
    }

    @Override
    public void initView() {
        imageViewer.imageLoader(new PhotoLoader());
        ivTitleRight.setImageResource(R.mipmap.ic_icon_title_more);

        momentData = new ArrayList<>();
        momentAdapter = new MomentAdapter(momentData);
        rvMoment.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvMoment.setAdapter(momentAdapter);

        smartRefresh.setOnRefreshListener(this);
        momentAdapter.setOnLoadMoreListener(this);

        momentAdapter.setOnItemClickCallback(this);
        momentAdapter.setOnItemClickListener(this);
        momentAdapter.setOnItemChildClickListener(this);
    }

    @Override
    public void initData() {

        addHeader();

        mPresenter.getMomentList(this, page, UserInfoUtil.getUserId());
    }

    @OnClick({R.id.iv_title_right, R.id.ll_null})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_title_right: //分享
                startActivity(new Intent(this, ShareActivity.class)
                        .putExtra(ShareActivity.INTENT_USER_ID, UserInfoUtil.getUserId()));
                break;

            case R.id.ll_null:
                startActivity(new Intent(this, MomentCreateActivity.class));
                break;
        }
    }

    /**
     * 添加头部布局
     */
    private void addHeader() {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_mine_userinfo_header, null);
        ivHead = view.findViewById(R.id.iv_head);
        tvNickName = view.findViewById(R.id.tv_nick_name);
        tvUserId = view.findViewById(R.id.tv_user_id);
        tvCity = view.findViewById(R.id.tv_city);
        tvSign = view.findViewById(R.id.tv_sign);
        ivSex = view.findViewById(R.id.iv_sex);
        tvEditUserInfo = view.findViewById(R.id.tv_edit_user_info);

        tvEditUserInfo.setOnClickListener(view1 -> startActivity(new Intent(MineUserInfoActivity.this, EditUserInfoActivity.class)));

        loadUser();
        momentAdapter.addHeaderView(view);
        momentAdapter.notifyDataSetChanged();
    }

    /**
     * 加载用户信息
     */
    private void loadUser() {
        GlideUtils.loadImgAsCircle(this, UserInfoUtil.getUserHead(), ivHead);
        tvNickName.setText(UserInfoUtil.getUserNickName());
        tvUserId.setText(getResources().getString(R.string.app_name) + "号：" + UserInfoUtil.getUserNumber());
        if (EmptyUtils.isEmpty(UserInfoUtil.getUserAddress())) {
            tvCity.setText("未知");
        } else {
            tvCity.setText(UserInfoUtil.getUserAddress());
        }
        if (EmptyUtils.isNotEmpty(UserInfoUtil.getUserSign())) {
            tvSign.setText(UserInfoUtil.getUserSign());
        }
        if (UserInfoUtil.getUserSex().equals(SexEnum.SEX_GRIL)) {
            ivSex.setImageResource(R.mipmap.ic_icon_sex_gril);
            ivSex.setVisibility(View.VISIBLE);
        } else if (UserInfoUtil.getUserSex().equals(SexEnum.SEX_BOY)) {
            ivSex.setImageResource(R.mipmap.ic_icon_sex_boy);
            ivSex.setVisibility(View.VISIBLE);
        } else {
            ivSex.setVisibility(View.GONE);
        }
        tvCity.setText(UserInfoUtil.getUserAddress());
    }

    /**
     * 用户信息修改成功，刷新UI
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void editUserInfoSuccess(EditUserInfoSuccesEvent event) {
        loadUser();
    }

    /**
     * 动态列表获取成功
     *
     * @param data
     */
    @Override
    public void momentResult(List<MomentBean> data) {
        smartRefresh.finishRefresh();
        momentAdapter.loadMoreComplete();
        try {
            if (isRefresh) {
                momentData.clear();
            }
            momentData.addAll(data);
            momentAdapter.notifyDataSetChanged();
            if (data.size() < Common.PAGE_COUNT) {
                momentAdapter.loadMoreEnd();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (momentData.size() > 0) {
            llNull.setVisibility(View.GONE);
        } else {
            llNull.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onFail() {
        smartRefresh.finishRefresh();
        momentAdapter.loadMoreFail();
    }

    /**
     * 点赞成功
     */
    @Override
    public void fabulousSuccess(int pos) {
        if (momentData.get(pos).getGreatstate() == 0) {
            momentData.get(pos).setGreatstate(1);
            momentData.get(pos).setGreatcount(momentData.get(pos).getGreatcount() + 1);
        } else {
            momentData.get(pos).setGreatstate(0);
            momentData.get(pos).setGreatcount(momentData.get(pos).getGreatcount() - 1);
        }
        momentAdapter.notifyDataSetChanged();
    }

    /**
     * 删除动态成功
     *
     * @param pos
     */
    @Override
    public void deleteSuccess(int pos) {
        momentData.remove(pos);
        momentAdapter.notifyDataSetChanged();
        showError("删除成功");
        if (momentData.size() <= 0) {
            rvMoment.setVisibility(View.GONE);
            llNull.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 收藏成功
     */
    @Override
    public void collectSuccess() {
        showError("收藏成功");
    }

    /**
     * 图片上传成功
     *
     * @param data
     */
    @Override
    public void upLoadImgSuccess(UpLoadImgBean data) {
        // 图片上传成功，收藏图片
        mPresenter.addChatCollect(this, null, data.getUrl(), UserInfoUtil.getUserId());
    }

    /**
     * 根据二维码获取用户信息成功
     *
     * @param data
     */
    @Override
    public void userInfoResult(UserInfoBean data) {
        if (data.getMember_id() == UserInfoUtil.getUserId()) {
            return;
        }
        if (data.getIs_buddy() == 1) {
            startActivity(new Intent(this, UserInfoActivity.class)
                    .putExtra(UserInfoActivity.INTENT_USER_ID, data.getMember_id()));
        } else {
            startActivity(new Intent(this, AddFriendActivity.class)
                    .putExtra(AddFriendActivity.INTENT_USER_ID, data.getMember_id())
                    .putExtra(AddFriendActivity.INTENT_TYPE, 2));
        }
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMoreRequested() {
        page++;
        isRefresh = false;
        mPresenter.getMomentList(this, page, UserInfoUtil.getUserId());
    }

    /**
     * 刷新
     *
     * @param refreshLayout
     */
    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 1;
        isRefresh = true;
        momentAdapter.setEnableLoadMore(true);
        mPresenter.getMomentList(this, page, UserInfoUtil.getUserId());
    }

    /**
     * 子控件点击
     *
     * @param adapter
     * @param view
     * @param position
     */
    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.iv_head: // 用户头像
                startActivity(new Intent(this, UserInfoActivity.class)
                        .putExtra(UserInfoActivity.INTENT_USER_ID, momentData.get(position).getMember_id()));
                break;

            case R.id.tv_fabulous: // 点赞
                mPresenter.momentFabulous(this, momentData.get(position).getDynamic_id(), position);
                break;

            case R.id.tv_commont: // 评论
                startActivity(new Intent(this, MomentInfoActivity.class)
                        .putExtra(MomentInfoActivity.INTENT_MOMENT_ID, momentData.get(position).getDynamic_id()));
                break;

            case R.id.iv_more: // 更多
                showMoreDialog(position);
                break;

            case R.id.tv_content:// 文本点击
                if (EmptyUtils.isNotEmpty(momentData.get(position).getLinkurl())) {
                    startActivity(new Intent(this, WebViewActivity.class)
                            .putExtra(WebViewActivity.INTENT_WEB_URL, momentData.get(position).getLinkurl()));
                } else {
                    startActivity(new Intent(this, MomentInfoActivity.class)
                            .putExtra(MomentInfoActivity.INTENT_MOMENT_ID, momentData.get(position).getDynamic_id()));
                }
                break;
        }
    }

    /**
     * 点击列表更多选项
     *
     * @param pos
     */
    private void showMoreDialog(int pos) {
        List<String> str = new ArrayList<>();
        str.add("删除动态");
        PublicRoundDialog roundDialog = new PublicRoundDialog(this, "请选择", str, (pos1, menu) -> {
            switch (menu) {
                case "删除动态":
                    mPresenter.deleteMoment(this, momentData.get(pos).getDynamic_id(), pos);
                    break;
            }
        });
        roundDialog.show();
    }

    /**
     * 列表点击
     *
     * @param adapter
     * @param view
     * @param position
     */
    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        startActivity(new Intent(this, MomentInfoActivity.class)
                .putExtra(MomentInfoActivity.INTENT_MOMENT_ID, momentData.get(position).getDynamic_id()));
    }

    /**
     * 查看大图
     *
     * @param position
     * @param list
     * @param viewGroup
     */
    @Override
    public void onItemClick(int position, List<String> list, ViewGroup viewGroup) {
        imageViewer.overlayStatusBar(true)
                .imageData(list)
                .bindViewGroup(viewGroup)
                .loadProgressUI(new PhotoProgressUi())
                .setOnItemLongPressListener((position1, imageView) -> {
                    saveImgToPhoto(imageView, list.get(position1));
                    return false;
                })
                .watch(position);
    }

    /**
     * 申请文件读写权限
     */
    private void registerPermission() {
        PermissionGen.with(this)
                .addRequestCode(Common.BASIC_PERMISSION_REQUEST_CODE)
                .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE
                        , Manifest.permission.READ_EXTERNAL_STORAGE)
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    /**
     * 权限申请失败
     */
    @PermissionFail(requestCode = Common.BASIC_PERMISSION_REQUEST_CODE)
    public void openFail() {
        ToastUtils.show("权限获取失败，无法保存图片");
    }

    /**
     * 权限申请成功
     */
    @PermissionSuccess(requestCode = Common.BASIC_PERMISSION_REQUEST_CODE)
    public void openSuccess() {
        ImageUtil.saveMyBitmap(this, ((BitmapDrawable) saveImageView.getDrawable()).getBitmap(), "chat_" + System.currentTimeMillis() + ".jpg");
    }

    /**
     * 保存图片到相册
     */
    private void saveImgToPhoto(ImageView imageView, String url) {

        saveImageView = imageView;
        new Thread(() -> {
            Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
            String result = QRCodeParseUtils.syncDecodeQRCode(bitmap);
            Message msg = new Message();
            msg.what = 0x03;
            Bundle bundle = new Bundle();
            bundle.putString("url", url);
            bundle.putString("qrcode", result);
            msg.obj = result;
            msg.setData(bundle);
            handler.sendMessage(msg);
        }).start();

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x02) {
                String result = msg.obj == null ? null : (String) msg.obj;
                LogUtils.d(result);
                if (EmptyUtils.isEmpty(result)) {
                    showError("未识别到二维码信息");
                    return;
                }
                if (result.contains("chat_number")) {
                    // 如果是多聊二维码，调用接口
                    mPresenter.getUserInfoByQrCode(MineUserInfoActivity.this, result);
                } else if (TextHttpUtil.hasNetUrlHead(result)) {
                    // 网页链接，跳转到web界面
                    startActivity(new Intent(MineUserInfoActivity.this, WebViewActivity.class)
                            .putExtra(WebViewActivity.INTENT_WEB_URL, result));
                } else {
                    // 都不是，直接展示结果
                    startActivity(new Intent(MineUserInfoActivity.this, CaptureResultActivity.class)
                            .putExtra(CaptureResultActivity.INTENT_RESULT, result));
                }
            } else if (msg.what == 0x03) {
                Bundle bundle = msg.getData();
                String qrcode = bundle.getString("qrcode");
                List<String> list = new ArrayList<>();
                list.add("发送给朋友");
                list.add("收藏");
                list.add("保存到相册");
                if (EmptyUtils.isNotEmpty(qrcode)) {
                    list.add("识别图中二维码");
                }
                PublicRoundDialog roundDialog = new PublicRoundDialog(MineUserInfoActivity.this, list, (pos, menu) -> {
                    switch (menu) {
                        case "发送给朋友":
                            collectImgUrl = bundle.getString("url");
                            startActivity(new Intent(MineUserInfoActivity.this, ChatShareUserActivity.class)
                                    .putExtra(ChatShareUserActivity.INTENT_FROM_TAG, 8));
                            break;

                        case "收藏":
                            collectImg(bundle.getString("url"));
                            break;
                        case "保存到相册":
                            registerPermission();
                            break;
                        case "识别图中二维码":
//                            new Thread(() -> {
//                                Bitmap bitmap = ((BitmapDrawable) saveImageView.getDrawable()).getBitmap();
//                                String result = QRCodeParseUtils.syncDecodeQRCode(bitmap);
//                                Message message = new Message();
//                                message.what = 0x02;
//                                message.obj = result;
//                                handler.sendMessage(message);
//                            }).start();
                            if (EmptyUtils.isEmpty(qrcode)) {
                                showError("未识别到二维码信息");
                                return;
                            }
                            if (qrcode.contains("chat_number")) {
                                // 如果是多聊二维码，调用接口
                                mPresenter.getUserInfoByQrCode(MineUserInfoActivity.this, qrcode);
                            } else if (TextHttpUtil.hasNetUrlHead(qrcode)) {
                                // 网页链接，跳转到web界面
                                startActivity(new Intent(MineUserInfoActivity.this, WebViewActivity.class)
                                        .putExtra(WebViewActivity.INTENT_WEB_URL, qrcode));
                            } else {
                                // 都不是，直接展示结果
                                startActivity(new Intent(MineUserInfoActivity.this, CaptureResultActivity.class)
                                        .putExtra(CaptureResultActivity.INTENT_RESULT, qrcode));
                            }
                            break;
                    }
                });
                roundDialog.show();
            }
        }
    };

    /**
     * 收藏图片
     */
    private void collectImg(String url) {
        LogUtils.d("url:" + url);
        DownLoadUtil.downLoadImg(url, new DownLoadUtil.OnDownLoadListener() {
            @Override
            public void success(String path) {
                mPresenter.upLoadImg(MineUserInfoActivity.this, path);
            }

            @Override
            public void fail() {
                showError("图片下载失败");
            }
        });
    }


    /**
     * 其他页面删除动态成功
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void momentDeleteSuccess(DeleteMomentEvent event) {
        for (int i = 0; i < momentData.size(); i++) {
            if (momentData.get(i).getDynamic_id() == event.getId()) {
                momentData.remove(i);
            }
        }
        momentAdapter.notifyDataSetChanged();
        if (momentData.size() <= 0) {
            rvMoment.setVisibility(View.GONE);
            llNull.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 动态发布成功
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void momentCreateSuccess(MomentCreateEvent event) {
        smartRefresh.autoRefresh();
    }

    /**
     * 评论删除成功
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void commentDeleteSuccess(DeleteCommentEvent event) {
        for (int i = 0; i < momentData.size(); i++) {
            if (momentData.get(i).getDynamic_id() == event.getId()) {
                momentData.get(i).setReviewcount(momentData.get(i).getReviewcount() - 1);
            }
        }
        momentAdapter.notifyDataSetChanged();
    }

    /**
     * 监听返回键
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean b = imageViewer.onKeyDown(keyCode, event);
        if (b) {
            return b;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 转发选择好友返回
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void selectUserResult(ChatShareUserEvent event) {
        if (event.getTag() == 8) {
            LogUtils.d("collectImgUrl:" + collectImgUrl);
            showLoading();
            DownLoadUtil.downLoadImg(collectImgUrl, new DownLoadUtil.OnDownLoadListener() {
                @Override
                public void success(String path) {
                    hideLoading();
                    ChatUtil.getInstance().sendImgMessage(MineUserInfoActivity.this,path, event.getBean().getHxusername(), ChatConstant.CHATTYPE_SINGLE,
                            event.getBean().getMember_id(), EmptyUtils.isEmpty(event.getBean().getRemarks_name()) ? event.getBean().getNickname() :
                                    event.getBean().getRemarks_name(), null);
                    showError("发送成功");
                }

                @Override
                public void fail() {
                    hideLoading();
                    showError("图片下载失败");
                }
            });
        }
    }
}
